<template>
  <div class="password-container">
    <el-card class="password-card" header="自习室管理员 - 密码修改">
      <el-form
          ref="formRef"
          :model="adminForm"
          :rules="rules"
          label-width="120px"
          class="password-form"
      >
        <el-form-item label="原始管理员密码" prop="oldPassword">
          <el-input
              show-password
              v-model="adminForm.oldPassword"
              placeholder="请输入当前管理员密码"
              class="input-field"
          ></el-input>
        </el-form-item>

        <el-form-item label="新管理员密码" prop="newPassword">
          <el-input
              show-password
              v-model="adminForm.newPassword"
              placeholder="请设置6-20位新密码"
              class="input-field"
          ></el-input>
          <div class="password-tip">
            <i class="el-icon-info"></i> 密码需包含数字和字母，避免简单密码
          </div>
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
              show-password
              v-model="adminForm.confirmPassword"
              placeholder="请再次输入新密码"
              class="input-field"
          ></el-input>
        </el-form-item>

        <div class="form-actions">
          <el-button
              type="primary"
              @click="updatePassword"
              class="submit-btn"
          >
            <i class="el-icon-check"></i> 确认修改密码
          </el-button>
          <el-button
              @click="handleCancel"
              class="cancel-btn"
          >
            <i class="el-icon-back"></i> 取消返回
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "AdminPassword",
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请确认新密码'));
      } else if (value !== this.adminForm.newPassword) {
        callback(new Error('两次输入的新密码不一致，请重新输入'));
      } else {
        callback();
      }
    };

    const validateNewPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入新密码'));
      } else if (value.length < 6 || value.length > 20) {
        callback(new Error('密码长度需在6-20个字符之间'));
      } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(value)) {
        callback(new Error('密码需同时包含数字和字母，提高安全性'));
      } else {
        callback();
      }
    };

    return {
      adminForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
        username: JSON.parse(localStorage.getItem('xm-user') || '{}').username || ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入原始管理员密码', trigger: 'blur' },
          { minLength: 6, message: '原始密码长度不能少于6个字符', trigger: 'blur' }
        ],
        newPassword: [
          { validator: validateNewPassword, required: true, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validateConfirmPassword, required: true, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    updatePassword() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const submitData = {
            username: this.adminForm.username,
            oldPassword: this.adminForm.oldPassword,
            newPassword: this.adminForm.newPassword
          };

          this.$request.put('/updatePassword', submitData).then(res => {
            if (res.code === '200') {
              localStorage.removeItem('xm-user');
              this.$message.success('管理员密码修改成功，即将跳转登录页');
              setTimeout(() => {
                this.$router.push('/login');
              }, 1500);
            } else {
              this.$message.error(`修改失败：${res.msg || '原始密码错误或服务器异常'}`);
            }
          }).catch(err => {
            this.$message.error('网络异常，无法连接自习室管理服务器');
            console.error('密码修改请求失败：', err);
          });
        }
      });
    },
    resetForm() {
      this.$refs.formRef.resetFields();
      this.$message.info('已重置密码表单');
    },
    // 合并取消逻辑到一个方法
    handleCancel() {
      this.resetForm();
      this.$router.go(-1);
    }
  }
};
</script>

<style scoped>
.password-container {
  padding: 30px;
  background-color: #f9f7ff;
  min-height: calc(100vh - 60px);
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.password-card {
  width: 600px;
  border-radius: 8px;
  box-shadow: 0 2px 15px rgba(123, 97, 255, 0.1);
  border: 1px solid #e0d9f7;
}

::v-deep .el-card__header {
  font-size: 18px;
  font-weight: 500;
  color: #5d46c3;
  border-bottom: 1px solid #e0d9f7;
  padding: 15px 20px;
}

.password-form {
  padding: 30px 20px 10px;
}

.input-field {
  border-color: #e0d9f7;
  border-radius: 4px;
}

::v-deep .input-field .el-input__inner:focus {
  border-color: #7b61ff;
  box-shadow: 0 0 0 2px rgba(123, 97, 255, 0.2);
}

::v-deep .el-form-item__label {
  font-weight: 500;
  color: #5d46c3;
}

.password-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #9a89e0;
  display: flex;
  align-items: center;
}

.password-tip .el-icon-info {
  margin-right: 4px;
  font-size: 12px;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.submit-btn {
  background-color: #7b61ff;
  border-color: #7b61ff;
  padding: 8px 25px;
}

::v-deep .submit-btn:hover {
  background-color: #6a54e0;
  border-color: #6a54e0;
}

.cancel-btn {
  color: #7b61ff;
  border-color: #e0d9f7;
  padding: 8px 25px;
}

::v-deep .cancel-btn:hover {
  background-color: #f0edff;
  border-color: #7b61ff;
}
</style>